package com.ye.util;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2022年04月23日 1:39
 */
@Component
public class ExceptionUtil {
    public static void handleException(BlockException ex) {
        System.out.println("Oops: " + ex.getClass().getCanonicalName());
    }

    public static String pojoHandleException(HttpServletRequest request, BlockException ex) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = new HashMap<>();
        for (String s : parameterMap.keySet()) {
            if (parameterMap.get(s).length == 1) {
                map.put(s, parameterMap.get(s)[0]);
            } else {
                map.put(s, parameterMap.get(s));
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",map);
        if (ex instanceof FlowException) {
            jsonObject.put("msg", "限流了");
            jsonObject.put("exception", ex.getClass().getCanonicalName());
        }
        return jsonObject.toJSONString();
    }
}
